package com.nexus.all.manager;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nexus.all.dao.UserMapper;
import com.nexus.all.model.User;
import com.nexus.bean.utils.CollectionsUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class UserManager extends ServiceImpl<UserMapper, User> {

    public User getByUserName(String username) {
        LambdaQueryWrapper<User> wrapper = User.gw();
        wrapper.eq(User::getUserName, username);
        return getOne(wrapper);
    }

    /**
     * 根据昵称获取用户信息
     *
     * @param nickName
     * @return
     */
    public User getByNickName(String nickName) {
        LambdaQueryWrapper<User> wrapper = User.gw();
        wrapper.eq(User::getNickName, nickName);
        return getOne(wrapper);
    }

    public User getByWxOpenId(String wxOpenId) {
        LambdaQueryWrapper<User> wrapper = User.gw();
        wrapper.eq(User::getWxOpenId, wxOpenId);
        return getOne(wrapper);
    }

    public void bindWxOpenIdByUserName(String userName, String openId) {
        LambdaUpdateWrapper<User> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(User::getWxOpenId, openId);
        wrapper.eq(User::getUserName, userName);
        update(wrapper);
    }

    /**
     * 修改用户密码
     *
     * @param userId
     * @param newPassword
     */
    public void updatePassword(Long userId, String newPassword) {
        LambdaUpdateWrapper<User> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(User::getUserPwd, newPassword);
        wrapper.eq(User::getId, userId);
        update(wrapper);
    }

    /**
     * 修改头像
     *
     * @param userId
     * @param avatarUrl
     */
    public void updateAvatar(Long userId, String avatarUrl) {
        LambdaUpdateWrapper<User> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(User::getAvatarUrl, avatarUrl);
        wrapper.eq(User::getId, userId);
        update(wrapper);
    }


    /**
     * 修改昵称、邮箱
     *
     * @param userId
     * @param nickName
     * @param email
     */
    public void updateNickNameAndEmail(Long userId, String nickName, String email) {
        LambdaUpdateWrapper<User> wrapper = new LambdaUpdateWrapper<>();
        wrapper.set(User::getNickName, nickName);
        wrapper.set(User::getEmail, email);
        wrapper.eq(User::getId, userId);
        update(wrapper);
    }

    public List<User> getByUserNames(List<String> userNames) {
        if (CollectionsUtil.isEmpty(userNames)) {
            return new ArrayList<>();
        }
        LambdaQueryWrapper<User> wrapper = User.gw();
        wrapper.in(User::getUserName, userNames);
        return list(wrapper);
    }
}
